package com.cmccgz.baselibrary.view.photoview;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cmccgz.baselibrary.R;
import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.image.GlideUtils;
import com.cmccgz.baselibrary.utils.FileUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.http.GET;
import retrofit2.http.Url;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class ImageShowActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_save, tv_back, tv_title;
    private PhotoViewPager vp_show;
    private List<String> imageUrls = new ArrayList<>();
    private int position;
    public static final String KEY_IMGE_URLS = "key_imge_urls";
    public static final String KEY_IMGE_POSITION = "key_imge_position";
    private MyPageAdapter adapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_imge_show;
    }

    @Override
    protected void initView() {
        tv_save = ((TextView) findViewById(R.id.tv_save));
        tv_back = ((TextView) findViewById(R.id.tv_back));
        tv_title = ((TextView) findViewById(R.id.tv_title));
        vp_show = ((PhotoViewPager) findViewById(R.id.vp_show));

        tv_save.setOnClickListener(this);
        tv_back.setOnClickListener(this);

        adapter = new MyPageAdapter(imageUrls, mContext);
        vp_show.setAdapter(adapter);
        vp_show.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ImageShowActivity.this.position = position;
                updateTitle();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        initDatas();
    }

    private void initDatas() {
        Intent intent = getIntent();
        List<String> list = (List<String>) intent.getSerializableExtra(KEY_IMGE_URLS);
        if (list != null) {
            imageUrls.addAll(list);
        }
        position = intent.getIntExtra(KEY_IMGE_POSITION, 0);
        adapter.notifyDataSetChanged();
        vp_show.setCurrentItem(position);
        updateTitle();
    }

    private void updateTitle() {

        int index = imageUrls.size() == 0 ? 0 : position + 1;
        tv_title.setText(index + "/" + imageUrls.size());
    }

    @Override
    protected void initFragment() {

    }

    @Override
    protected void beforePermission() {

    }

    @Override
    protected int setSystemBarColorId() {
        return R.color.black;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            int currentItem = vp_show.getCurrentItem();
            if (currentItem >= 0 && currentItem < imageUrls.size()) {
                final String imgUrl = imageUrls.get(currentItem);
                final String fileName = getFileName(imgUrl);
                final File file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "cmccgz", fileName);
                Log.e(ImageShowActivity.class.getSimpleName(), "保存图片的文件路径：" + file.getAbsolutePath());
                if (file.exists()) {
                    ToastUtils.show(mContext, "保存成功！图片路径为：" + file.getAbsolutePath());
                    return;
                }
                //保存本地
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://www.cmccgz.com/")
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
                RetrofitServices retrofitServices = retrofit.create(RetrofitServices.class);
                retrofitServices.downFile(imgUrl)
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .map(new Func1<ResponseBody, InputStream>() {
                            @Override
                            public InputStream call(ResponseBody responseBody) {
                                if (responseBody == null) {
                                    return null;
                                }
                                return responseBody.byteStream();
                            }
                        })
                        .observeOn(Schedulers.computation())
                        .doOnNext(new Action1<InputStream>() {
                            @Override
                            public void call(InputStream is) {
                                try {
                                    FileUtils.writeFile(is, file);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<InputStream>() {
                            @Override
                            public void onCompleted() {
                                ToastUtils.show(mContext, "保存成功！图片路径为：" + file.getAbsolutePath());
                                mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                            }

                            @Override
                            public void onError(Throwable e) {
                                ToastUtils.show(mContext, "保存失败！");
                            }

                            @Override
                            public void onNext(InputStream inputStream) {

                            }
                        });

            } else
                ToastUtils.show(mContext, "保存失败");
        } else if (id == R.id.tv_back) {
            finish();
        }
    }

    @NonNull
    private String getFileName(String imgUrl) {
        int index = imgUrl.lastIndexOf("/");
        Pattern p = Pattern.compile("[0-9a-zA-Z]+");
        String substring = imgUrl.substring(index);
        Matcher matcher = p.matcher(substring);
        String fileName = "";
        while (matcher.find()) {
            fileName += matcher.group();
        }
        return fileName + ".jpg";
    }

    class MyPageAdapter extends PagerAdapter {
        private List<String> imgUrls = new ArrayList<>();
        private Context context;

        public MyPageAdapter(List<String> imgUrls, Context context) {
            this.imgUrls = imgUrls;
            this.context = context;
        }

        @Override
        public int getCount() {
            return imgUrls.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(context);
            GlideUtils.loadImage(context, imgUrls.get(position), photoView);
            container.addView(photoView);
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object != null && object instanceof View) {
                container.removeView(((View) object));
            }
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    public interface RetrofitServices {
        @GET
        Observable<ResponseBody> downFile(@Url String url);
    }
}
